package com.win.logback;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

import static java.util.concurrent.Executors.newFixedThreadPool;

@Component
public class LoggerPusher {

    public static final LinkedBlockingQueue<LoggerMessage> QUEUE = new LinkedBlockingQueue<>(1000);

    /**
     * 使用 SimpMessagingTemplate 向浏览器发送信息
     */
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @PostConstruct
    public void init() {
        // 子线程开始从管道流读取数据
//        Thread thread = new Thread(() -> {
//            while (true) {
//                try {
//                    if (LoggerPusher.QUEUE.size() > 0) {
//                        LoggerMessage message = LoggerPusher.QUEUE.take();
//                        messagingTemplate.convertAndSend("/sub/log", JSONObject.toJSONString(message));
//                    }
//                    //noinspection BusyWait
//                    Thread.sleep(1);
//                } catch (Exception ignored) {
//                }
//            }
//        });
//        thread.setDaemon(Boolean.TRUE);
//        thread.setName("socket-log");
//        thread.start();
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(Boolean.TRUE).setNamePrefix("socket-log").build();
        new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), threadFactory).execute(() -> {
            while (true) {
                try {
                    if (LoggerPusher.QUEUE.size() > 0) {
                        LoggerMessage message = LoggerPusher.QUEUE.take();
                        messagingTemplate.convertAndSend("/sub/log", JSONObject.toJSONString(message));
                    }
                    //noinspection BusyWait
                    Thread.sleep(1);
                } catch (Exception ignored) {
                }
            }
        });
    }
}
